package com.taotao.async.task.spring.handler;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.util.Set;

public class TaskHandlerScanner extends ClassPathBeanDefinitionScanner {

    public TaskHandlerScanner(BeanDefinitionRegistry registry) {
        super(registry, false);//默认只扫描@Component与@ManagedBean建议取消默认的
        //重新添加过滤规则  类似注解组件扫描
        addIncludeFilter(new AnnotationTypeFilter(TaskHandler.class));
    }

    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> definitionHolders = super.doScan(basePackages);
        handleBeanDefinitionHolder(definitionHolders);//对扫描结果进行拦截处理
        return definitionHolders;
    }

    //对扫描对象的条件过滤
//    @Override
//    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
//
//
//        return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent();
//    }

    private void handleBeanDefinitionHolder(Set<BeanDefinitionHolder> definitionHolders) {
        for (BeanDefinitionHolder holder : definitionHolders) {
            BeanDefinition definition = holder.getBeanDefinition();
            //保留原来的接口
            String className = definition.getBeanClassName();
            System.out.println("--------------------" + className);
//            //替换Bean的实现类
//            definition.setBeanClassName("com.sk.api.mapper.factory.ApiMapperFactoryBean");
//            MutablePropertyValues values = definition.getPropertyValues();
//            //通过Bean的名字添加引用属性
//            values.add("apiMapper",new RuntimeBeanReference("apiMapper"));
//            //若类型不匹配Spring的类型转换器会生效
//            values.add("targetClass",className);
//            log.info("ApiMapper Is Mapper:"+className);
        }
    }

}
